package com.seeyon.apps.ebs.rc.utils;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.ebs.rc.dao.RcDao;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.template.manager.TemplateManager;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgLevel;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.JDBCAgent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class RcUtils {
    private static final Log log = LogFactory.getLog(RcUtils.class);
    private static ColManager colManager = (ColManager) AppContext.getBean("colManager");
    private static EnumManager enumManager = (EnumManager) AppContext.getBean("enumManagerNew");
    private static OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
    private static FormApi4Cap4 cap4FormManager = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
    private static TemplateManager templateManager = (TemplateManager) AppContext.getBean("templateManager");
    private static RcDao rcDao = (RcDao) AppContext.getBean("ebsRcDao");
    private static SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
    private static RcDao ebsRcDao = (RcDao) AppContext.getBean("ebsRcDao");
    private static String scheduleDutiesName = AppContext.getSystemProperty("ebsRc.scheduleDutiesName");
    private static String scheduleArchiveCode = AppContext.getSystemProperty("ebsRc.scheduleArchiveCode");
    private static String relocationCode = AppContext.getSystemProperty("relocationData.relocationCode");

    /**
     * 功能:查询日程档案中某员工某天的日程信息--区分出差类型---国际出差-1、国内出差--4
     * @Date: 2025/1/24
     */
    public static int personalScheduleNew(String day, Long memberId, JDBCAgent jdbcAgent) throws Exception {
        int rySatte = 0;
        try {
            V3xOrgMember member = orgManager.getMemberById(memberId);
            if (member == null) {
                log.info("未找到成员ID：" + memberId);
                return rySatte;
            }

            log.info("查询人员：{"+ member.getName()+"} - 在 {"+day+"} 的动迁状态！！！");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate dayDate = LocalDate.parse(day, formatter);
            LocalDate createDate = member.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            // if (createDate.isBefore(dayDate)) {
            FormBean cap4FormBean = cap4FormManager.getFormByFormCode(scheduleArchiveCode);
            if (cap4FormBean != null) {
                FormFieldBean bhBean = cap4FormBean.getFieldBeanByDisplay("编号");
                FormFieldBean xmBean = cap4FormBean.getFieldBeanByDisplay("姓名");
                FormFieldBean lxBean = cap4FormBean.getFieldBeanByDisplay("类型");
                FormFieldBean ksrqBean = cap4FormBean.getFieldBeanByDisplay("开始日期");
                FormFieldBean jsrqBean = cap4FormBean.getFieldBeanByDisplay("结束日期");
                FormFieldBean tripTypeBean = cap4FormBean.getFieldBeanByDisplay("出差类型");

                Map<String, Object> formMap = new HashMap<>();
                formMap.put("tableName", bhBean.getOwnerTableName());
                formMap.put("xmFie", xmBean.getName());
                formMap.put("lxFie", lxBean.getName());
                formMap.put("ksrqFie", ksrqBean.getName());
                formMap.put("jsrqFie", jsrqBean.getName());
                formMap.put("xm", member.getId());
                formMap.put("dqDate", java.sql.Date.valueOf(LocalDate.parse(day)));

                List<Map<String, Object>> dqDbList = rcDao.getAPeopleAllDepIdsByNameAndDate(formMap);
                if (dqDbList != null && !dqDbList.isEmpty()) {
                    for (Map<String, Object> map : dqDbList) {
                        if (map.containsKey(lxBean.getName()) && map.get(lxBean.getName()) != null) {
                            try {
                                Long enumValueId = Long.parseLong(map.get(lxBean.getName()).toString());
                                CtpEnumItem lxEnumItem = enumManager.getCtpEnumItem(enumValueId);
                                if (lxEnumItem != null) {
                                    String label = lxEnumItem.getLabel();
                                    if ("出差".equals(label)) {
                                        Object tripTypeObj = map.get(tripTypeBean.getName());
                                        if (tripTypeObj != null && !"".equals(tripTypeObj)){
                                            CtpEnumItem cacheEnumItem = enumManager.getCacheEnumItem(Long.valueOf(tripTypeObj.toString()));
                                            if (cacheEnumItem!=null){
                                                String tripTypeLabel = cacheEnumItem.getLabel();
                                                if ("International business trip".equals(tripTypeLabel)){//国际出差
                                                    rySatte = 1;
                                                }else{//国内出差
                                                    rySatte = 4;
                                                }
                                            }
                                        }else{//出差类型为空的，默认为 国际出差
                                            rySatte = 1;
                                        }
                                    } else if ("在岗".equals(label) && rySatte != 1) {
                                        rySatte = 2;
                                    } else if ("休假".equals(label) && rySatte != 1 && rySatte != 2) {
                                        rySatte = 3;
                                    }else {
                                        rySatte = 2;
                                    }
                                }
                            } catch (NumberFormatException e) {
                                log.error("解析枚举值失败：{}", e);
                            }
                        }
                    }
                }else {
                    rySatte = 2;
                }
            } else {
                log.info("动迁档案不存在！！！");
            }
            // } else {
            //     log.info("人员账号创建时间在 {"+day+"} 之后！！！" );
            // }
        } catch (Exception e) {
            log.error("查询日程信息时发生异常：{}", e);
        }

        log.info("day={} - 人员状态：时间"+ day+"状态1："+ rySatte);
        return rySatte;
    }

    /**
    * 功能:查询日程档案中某员工某天的日程信息
    * @Date: 2025/1/24
    */
    public static int personalSchedule(String day, Long memberId, JDBCAgent jdbcAgent) throws Exception {
        int rySatte = 0;
        try {
            V3xOrgMember member = orgManager.getMemberById(memberId);
            if (member == null) {
                log.info("未找到成员ID：" + memberId);
                return rySatte;
            }

            log.info("查询人员：{"+ member.getName()+"} - 在 {"+day+"} 的动迁状态！！！");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate dayDate = LocalDate.parse(day, formatter);
            LocalDate createDate = member.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            // if (createDate.isBefore(dayDate)) {
            FormBean cap4FormBean = cap4FormManager.getFormByFormCode(scheduleArchiveCode);
            if (cap4FormBean != null) {
                FormFieldBean bhBean = cap4FormBean.getFieldBeanByDisplay("编号");
                FormFieldBean xmBean = cap4FormBean.getFieldBeanByDisplay("姓名");
                FormFieldBean lxBean = cap4FormBean.getFieldBeanByDisplay("类型");
                FormFieldBean ksrqBean = cap4FormBean.getFieldBeanByDisplay("开始日期");
                FormFieldBean jsrqBean = cap4FormBean.getFieldBeanByDisplay("结束日期");

                Map<String, Object> formMap = new HashMap<>();
                formMap.put("tableName", bhBean.getOwnerTableName());
                formMap.put("xmFie", xmBean.getName());
                formMap.put("lxFie", lxBean.getName());
                formMap.put("ksrqFie", ksrqBean.getName());
                formMap.put("jsrqFie", jsrqBean.getName());
                formMap.put("xm", member.getId());
                formMap.put("dqDate", java.sql.Date.valueOf(LocalDate.parse(day)));

                List<Map<String, Object>> dqDbList = rcDao.getAPeopleAllDepIdsByNameAndDate(formMap);
                if (dqDbList != null && !dqDbList.isEmpty()) {
                    for (Map<String, Object> map : dqDbList) {
                        if (map.containsKey(lxBean.getName()) && map.get(lxBean.getName()) != null) {
                            try {
                                Long enumValueId = Long.parseLong(map.get(lxBean.getName()).toString());
                                CtpEnumItem lxEnumItem = enumManager.getCtpEnumItem(enumValueId);
                                if (lxEnumItem != null) {
                                    String label = lxEnumItem.getLabel();
                                    if ("出差".equals(label)) {
                                        rySatte = 1;
                                        break;
                                    } else if ("在岗".equals(label) && rySatte != 1) {
                                        rySatte = 2;
                                    } else if ("休假".equals(label) && rySatte != 1 && rySatte != 2) {
                                        rySatte = 3;
                                    }else {
                                        rySatte = 2;
                                    }
                                }
                            } catch (NumberFormatException e) {
                                log.error("解析枚举值失败：{}", e);
                            }
                        }
                    }
                }else {
                    rySatte = 2;
                }
            } else {
                log.info("动迁档案不存在！！！");
            }
            // } else {
            //     log.info("人员账号创建时间在 {"+day+"} 之后！！！" );
            // }
        } catch (Exception e) {
            log.error("查询日程信息时发生异常：{}", e);
        }

        log.info("day={} - 人员状态：时间"+ day+"状态1："+ rySatte);
        return rySatte;
    }

    /**
     * 根据页数和每页的数据条数，计算数据的起始和结束范围（从1开始计数）
     *
     * @param page     当前页数（从1开始）
     * @param pageSize 每页的数据条数
     * @return 包含起始和结束数据条数的数组，计数从1开始
     */
    public static JSONObject getRange(int page, int pageSize) {
        JSONObject result = new JSONObject();
        if (page < 1 || pageSize < 1) {
            return result;
        }
        int start = (page - 1) * pageSize + 1; // 起始数据条数（从1开始）
        int end = start + pageSize - 1; // 结束数据条数
        result.put("start", start);
        result.put("end", end);
        return result;
    }


    /**
    * 功能:查询部门下所有 人员当天的动迁信息
    * @Date: 2025/2/11
    */
    public static JSONObject personalSchedule(JSONObject parma,JDBCAgent jdbcAgent)throws Exception {
        long onSite = 0;
        long bt = 0;
        long rl = 0;
        Long deptId = parma.getLong("deptId");
        String now = parma.getString("now");
        V3xOrgDepartment department = orgManager.getDepartmentById(deptId);
        //List<OrgMember> allMembers = rcDao.getAllMemberByDepId(department.getId());
        List<Map<String, Object>> realDeptMembers = rcDao.getRealDeptMembers(department.getId());
        List<V3xOrgMember> allMembers = new ArrayList<>();
        for (Map<String, Object> map : realDeptMembers){
            long memberId = Long.parseLong(String.valueOf(map.get("id")));
            allMembers.add(orgManager.getMemberById(memberId));
        }
        if (allMembers != null){
            for (V3xOrgMember orgMember : allMembers) {
                int rySatte = RcUtils.personalSchedule(now, orgMember.getId(),jdbcAgent);
                if (rySatte == 1){
                    bt++;
                } else if (rySatte == 2) {
                    onSite++;
                } else if (rySatte == 3) {
                    rl++;
                }else if (rySatte == 0){
                    onSite++;
                }
            }
        }
        parma.put("onSite", onSite);
        parma.put("bt",bt);
        parma.put("rl",rl);
        return parma;
    }

    /**
    * 功能:获取人员日程权限
    * @Date: 2025/1/23
    */
    public static JSONObject personalScheduleRoles(Long memberId)throws Exception {
        orgManager = (OrgManager) AppContext.getBean("orgManager");
        JSONObject dataJson = new JSONObject();
        V3xOrgMember member = orgManager.getMemberById(memberId);
        V3xOrgLevel level = orgManager.getLevelById(member.getOrgLevelId());
        Set<Long> depSet = new LinkedHashSet<>();
        JSONObject depIdName = new JSONObject();
        if (scheduleDutiesName!=null && !scheduleDutiesName.isEmpty()){
            String[] levelNames = scheduleDutiesName.split(",");
            for (String levelName : levelNames) {
                if (levelName.equals(level.getName())){
                    dataJson.put("grade",1);
                    dataJson.put("zgDepId",depSet);
                    return dataJson;
                }
            }
        }
        //查询主管部门信息
        List<Map<String, Object>> zgDepIds = ebsRcDao.getAPeopleAllDepIds(memberId);
        if (zgDepIds!=null && !zgDepIds.isEmpty()){
            dataJson.put("grade",2);
            for (Map<String, Object> zgDep : zgDepIds) {
                Long depId = Long.valueOf(zgDep.get("objective0_id").toString());
                //排出不需要的部门
                Map<String, Object> needDeptById = rcDao.getNeedDeptById(depId);
                if (needDeptById == null|| needDeptById.isEmpty()){
                    continue;
                }
                V3xOrgDepartment department = orgManager.getDepartmentById(depId);
                if (department != null){
                    depSet.add(depId);
                    depIdName.put(needDeptById.get("id").toString(),needDeptById.get("jc"));
                }
            }
            dataJson.put("zgDepIdName",depIdName);
            dataJson.put("zgDepId",depSet);
            log.info("主管部门信息");
            return dataJson;
        }
        //普通人员权限
        dataJson.put("grade",3);
        dataJson.put("zgDepId",depSet);
        return dataJson;
    }

    /**
    * 功能:将一个月拆分
    * @Date: 2025/1/23
    */
    public static List<String> getAllDaysInMonth(int year, int month) throws Exception{
        List<String> dates = new ArrayList<>();
        LocalDate startDate = LocalDate.of(year, month, 1);
        int daysInMonth = startDate.lengthOfMonth();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (int day = 1; day <= daysInMonth; day++) {
            LocalDate date = startDate.withDayOfMonth(day);
            dates.add(date.format(formatter));
        }
        return dates;
    }

    /**
    * 功能:refreshSchedule
    * @Date: 2025/1/24
    */
    public static void refreshSchedule()throws Exception{
        FormBean cap4FormBean = cap4FormManager.getFormByFormCode(relocationCode);
        FormFieldBean noBean = cap4FormBean.getFieldBeanByDisplay("NO");
        FormFieldBean nameBean = cap4FormBean.getFieldBeanByDisplay("Name");

        FormBean cap4DbFormBean = cap4FormManager.getFormByFormCode(scheduleArchiveCode);
        FormFieldBean bhBean = cap4DbFormBean.getFieldBeanByDisplay("编号");
        FormFieldBean xmBean = cap4DbFormBean.getFieldBeanByDisplay("姓名");
        FormFieldBean lxBean = cap4DbFormBean.getFieldBeanByDisplay("类型");
        FormFieldBean ksrqBean = cap4DbFormBean.getFieldBeanByDisplay("开始日期");
        FormFieldBean jsrqBean = cap4DbFormBean.getFieldBeanByDisplay("结束日期");
        FormFieldBean fqsjBean = cap4DbFormBean.getFieldBeanByDisplay("发起时间");
        FormFieldBean wybsBean = cap4DbFormBean.getFieldBeanByDisplay("唯一标识");
        Map<String,Object> dqDbMap = new HashMap<>();
        dqDbMap.put("tableName", bhBean.getOwnerTableName());
        dqDbMap.put("bhFie", bhBean.getName());
        dqDbMap.put("fqsjFie", fqsjBean.getName());
        dqDbMap.put("wybsFie", wybsBean.getName());
        List<Map<String, Object>> allSchedule = rcDao.getAllSchedule(dqDbMap);
        if (allSchedule != null){
            for (Map<String, Object> dqDb : allSchedule){
                Long formMainId = Long.valueOf(dqDb.get("id").toString());
                FormDataMasterBean master = cap4FormManager.getDataMasterBeanById(formMainId, cap4DbFormBean, null);
                Map<String, Object> dqFormMap = new HashMap<>();
                dqFormMap.put("tableName", noBean.getOwnerTableName());
                dqFormMap.put("noFie", noBean.getName());
                dqFormMap.put("no", master.getFieldValue(bhBean.getName()));
                List<Map<String, Object>> allScheduleByNumber = rcDao.getAllScheduleByNumber(dqFormMap);
                if (allScheduleByNumber != null && !allScheduleByNumber.isEmpty()){
                    master.addFieldValue(fqsjBean.getName(), allScheduleByNumber.get(0).get("start_date"));
                    cap4FormManager.insertOrUpdateMasterData(master);
                    log.info("查询需要更新发起时间的动迁流程表！！！");
                }
            }
        }
        log.info("sss");
    }
}
